"""
HiAgent智能体中心API路由
整合应用中心、个人智能体、收藏等功能
"""
from fastapi import APIRouter, HTTPException, Query, Body
from pydantic import BaseModel, Field
from typing import List, Optional
import sys
import os
import logging

logger = logging.getLogger(__name__)

# 动态导入HiAgent模块
try:
    # 使用绝对导入路径
    from src.llm.hiagent_app.services.app_service import AppService
    from src.llm.hiagent_app.services.favorite_service import FavoriteService
    from src.llm.hiagent_app.services.personal_agent_service import PersonalAgentService
    from src.llm.hiagent_app.services.workflow_service import WorkflowService
    from src.llm.hiagent_app.services.plugin_service import PluginService
    from src.llm.hiagent_app.services.agent_knowledge_service import AgentKnowledgeService
    from src.llm.hiagent_app.models.hiagent_models import AppType, ListOption, ListAppCenterFilter, ListAppBriefsFilter

    logger.info("HiAgent services loaded successfully")
except Exception as e:
    logger.error(f"Failed to load HiAgent services: {e}")
    # 提供占位符以避免导入错误
    AppService = None
    FavoriteService = None
    PersonalAgentService = None
    WorkflowService = None
    PluginService = None
    AgentKnowledgeService = None
    AppType = None
    ListOption = None
    ListAppCenterFilter = None
    ListAppBriefsFilter = None

router = APIRouter(
    prefix="/api/v1/hiagent",
    tags=["HiAgent Center"],
    responses={404: {"description": "Not found"}}
)

# 初始化服务
app_service = AppService() if AppService else None
favorite_service = FavoriteService() if FavoriteService else None
personal_agent_service = PersonalAgentService() if PersonalAgentService else None
workflow_service = WorkflowService() if WorkflowService else None
plugin_service = PluginService() if PluginService else None
agent_knowledge_service = AgentKnowledgeService() if AgentKnowledgeService else None


def check_service_available():
    """检查服务是否可用"""
    if not app_service or not favorite_service or not personal_agent_service:
        raise HTTPException(
            status_code=503,
            detail="HiAgent服务暂时不可用，请检查配置"
        )


def check_workflow_service_available():
    """检查工作流服务是否可用"""
    if not workflow_service:
        raise HTTPException(
            status_code=503,
            detail="工作流服务暂时不可用，请检查配置"
        )


def check_plugin_service_available():
    """检查插件服务是否可用"""
    if not plugin_service:
        raise HTTPException(
            status_code=503,
            detail="插件服务暂时不可用，请检查配置"
        )


# ==================== 请求/响应模型 ====================

class StandardResponse(BaseModel):
    """标准响应格式"""
    success: bool
    message: Optional[str] = None
    data: Optional[dict] = None


class PaginationParams(BaseModel):
    """分页参数"""
    page: int = Field(1, ge=1, description="页码")
    page_size: int = Field(20, ge=1, le=100, description="每页数量")


class AppCenterFilterParams(BaseModel):
    """应用中心筛选参数"""
    category_id: Optional[str] = Field(None, description="分类ID")
    app_types: Optional[List[str]] = Field(None, description="应用类型列表")
    keyword: Optional[str] = Field(None, description="关键词搜索")
    is_published: Optional[bool] = Field(None, description="是否已发布")


class PersonalAgentFilterParams(BaseModel):
    """个人智能体筛选参数"""
    keyword: Optional[str] = Field(None, description="关键词搜索")
    app_type: Optional[str] = Field(None, description="应用类型")
    is_published: Optional[bool] = Field(None, description="是否已发布")


class CreateAgentRequest(BaseModel):
    """创建智能体请求"""
    name: str = Field(..., description="智能体名称")
    description: str = Field(..., description="智能体描述")
    workspace_id: str = Field(..., description="工作空间ID(必填)")
    app_type: str = Field("Chat", description="应用类型")
    icon: Optional[str] = Field(None, description="图标URL")
    background: Optional[str] = Field(None, description="背景颜色")
    image: Optional[str] = Field(None, description="自定义图片URL")
    workflow_ids: Optional[List[str]] = Field(None, description="工作流ID列表")


class UpdateAgentRequest(BaseModel):
    """更新智能体请求"""
    name: Optional[str] = Field(None, description="智能体名称")
    description: Optional[str] = Field(None, description="智能体描述")
    icon: Optional[str] = Field(None, description="图标URL")
    background: Optional[str] = Field(None, description="背景颜色")
    image: Optional[str] = Field(None, description="自定义图片URL")
    http_runnable: Optional[bool] = Field(None, description="HTTP是否可运行")
    api_runnable: Optional[bool] = Field(None, description="API是否可运行")
    workflow_ids: Optional[List[str]] = Field(None, description="工作流ID列表")


class CreateAgentWithKnowledgeRequest(BaseModel):
    """创建Agent并配置知识库请求"""
    agent_name: str = Field(..., description="Agent名称", min_length=1)
    workspace_id: str = Field(..., description="工作空间ID（必填）", min_length=1)
    source_agent_id: str = Field(..., description="源智能体ID（必填，从该智能体复制配置）", min_length=1)
    knowledge_name: Optional[str] = Field(None, description="知识库名称（可选，默认为{agent_name}_知识库）")
    agent_description: Optional[str] = Field(None, description="Agent描述（可选）")


# ==================== 应用中心API ====================

@router.get("/app-center/categories", summary="获取应用中心分类列表")
async def list_app_center_categories(
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取应用中心的所有分类"""
    check_service_available()
    try:
        categories = app_service.list_app_center_categories(workspace_id)
        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "categories": [cat.__dict__ for cat in categories],
                "total": len(categories)
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取分类失败: {str(e)}")


@router.get("/app-center/list", summary="获取应用中心列表")
async def list_app_center(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    category_id: Optional[str] = Query(None, description="分类ID"),
    keyword: Optional[str] = Query(None, description="关键词"),
    app_types: Optional[str] = Query(None, description="应用类型列表，逗号分隔，如：Chat,Workflow"),
    is_published: Optional[bool] = Query(None, description="是否已发布"),
    published_agent_mode: Optional[str] = Query(None, description="已发布智能体模式：Single/Multi"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取应用中心的应用列表

    支持的筛选条件：
    - category_id: 按分类ID筛选
    - keyword: 关键词搜索（应用名称或描述）
    - app_types: 应用类型列表，多个类型用逗号分隔（Chat, Completion, Workflow）
    - is_published: 是否已发布
    - published_agent_mode: 已发布智能体模式（Single, Multi）
    """
    try:
        list_opt = ListOption(page=page, page_size=page_size)

        # 解析app_types参数
        parsed_app_types = None
        if app_types:
            try:
                # 将逗号分隔的字符串转换为AppType枚举列表
                type_list = [t.strip() for t in app_types.split(',')]
                parsed_app_types = [AppType[t.upper()] for t in type_list if t]
            except (KeyError, ValueError) as e:
                raise HTTPException(
                    status_code=400,
                    detail=f"无效的应用类型: {app_types}。有效值: Chat, Completion, Workflow"
                )

        # 解析published_agent_mode参数
        parsed_agent_mode = None
        if published_agent_mode:
            try:
                parsed_agent_mode = AgentMode[published_agent_mode.upper()]
            except (KeyError, ValueError):
                raise HTTPException(
                    status_code=400,
                    detail=f"无效的智能体模式: {published_agent_mode}。有效值: Single, Multi"
                )

        filter_opt = ListAppCenterFilter(
            category_id=category_id,
            keyword=keyword,
            app_types=parsed_app_types,
            is_published=is_published,
            published_agent_mode=parsed_agent_mode
        )

        apps, total = app_service.list_app_center(list_opt, filter_opt, workspace_id)

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [app.__dict__ for app in apps],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取应用列表失败: {str(e)}")


@router.get("/app-center/favorites", summary="获取收藏的应用列表")
async def list_favorite_app_center(
    last_favorite_id: Optional[str] = Query(None, description="最后一个收藏ID（用于分页）"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    category_id: Optional[str] = Query(None, description="分类ID"),
    keyword: Optional[str] = Query(None, description="关键词"),
    app_types: Optional[str] = Query(None, description="应用类型列表，逗号分隔，如：Chat,Workflow"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取用户收藏的应用列表

    支持的筛选条件：
    - category_id: 按分类ID筛选
    - keyword: 关键词搜索
    - app_types: 应用类型列表，多个类型用逗号分隔（Chat, Completion, Workflow）
    """
    try:
        # 解析app_types参数
        parsed_app_types = None
        if app_types:
            try:
                type_list = [t.strip() for t in app_types.split(',')]
                parsed_app_types = [AppType[t.upper()] for t in type_list if t]
            except (KeyError, ValueError):
                raise HTTPException(
                    status_code=400,
                    detail=f"无效的应用类型: {app_types}。有效值: Chat, Completion, Workflow"
                )

        filter_opt = None
        if category_id or keyword or parsed_app_types:
            filter_opt = ListAppCenterFilter(
                category_id=category_id,
                keyword=keyword,
                app_types=parsed_app_types
            )

        apps, last_id, has_more = app_service.list_favorite_app_center(
            last_favorite_id, page_size, filter_opt, workspace_id
        )

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [app.__dict__ for app in apps],
                "last_favorite_id": last_id,
                "has_more": has_more
            }
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取收藏列表失败: {str(e)}")


@router.get("/app-center/recently-used", summary="获取最近使用的应用列表")
async def list_recently_used_app_center(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    category_id: Optional[str] = Query(None, description="分类ID"),
    keyword: Optional[str] = Query(None, description="关键词"),
    app_types: Optional[str] = Query(None, description="应用类型列表，逗号分隔，如：Chat,Workflow"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取最近使用的应用列表

    支持的筛选条件：
    - category_id: 按分类ID筛选
    - keyword: 关键词搜索
    - app_types: 应用类型列表，多个类型用逗号分隔（Chat, Completion, Workflow）
    """
    try:
        list_opt = ListOption(page=page, page_size=page_size)

        # 解析app_types参数
        parsed_app_types = None
        if app_types:
            try:
                type_list = [t.strip() for t in app_types.split(',')]
                parsed_app_types = [AppType[t.upper()] for t in type_list if t]
            except (KeyError, ValueError):
                raise HTTPException(
                    status_code=400,
                    detail=f"无效的应用类型: {app_types}。有效值: Chat, Completion, Workflow"
                )

        filter_opt = None
        if category_id or keyword or parsed_app_types:
            filter_opt = ListAppCenterFilter(
                category_id=category_id,
                keyword=keyword,
                app_types=parsed_app_types
            )

        apps, total = app_service.list_recently_used_app_center(list_opt, filter_opt, workspace_id)

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [app.__dict__ for app in apps],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取最近使用列表失败: {str(e)}")


@router.get("/app-center/{app_id}", summary="获取应用详情")
async def get_app_center_detail(
    app_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取应用中心应用的详细信息

    注意：此路由必须放在所有/app-center/固定路径路由之后，
    否则会错误匹配如/app-center/favorites等路径
    """
    try:
        app = app_service.get_app_center_detail(app_id, workspace_id)
        if not app:
            raise HTTPException(status_code=404, detail="应用不存在")

        return StandardResponse(
            success=True,
            message="获取成功",
            data={"app": app.__dict__}
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取应用详情失败: {str(e)}")


# ==================== 收藏管理API ====================

@router.post("/favorites/{app_id}/add", summary="添加到收藏")
async def add_to_favorites(
    app_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """将应用添加到收藏列表"""
    try:
        success = favorite_service.add_to_favorites(app_id, workspace_id)
        return StandardResponse(
            success=success,
            message="添加成功" if success else "添加失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加收藏失败: {str(e)}")


@router.delete("/favorites/{app_id}", summary="从收藏移除")
async def remove_from_favorites(
    app_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """从收藏列表移除应用"""
    try:
        success = favorite_service.remove_from_favorites(app_id, workspace_id)
        return StandardResponse(
            success=success,
            message="移除成功" if success else "移除失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"移除收藏失败: {str(e)}")


@router.get("/favorites/homepage", summary="获取首页收藏列表")
async def list_favorites_in_homepage(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取首页右侧显示的收藏列表"""
    try:
        list_opt = ListOption(page=page, page_size=page_size)
        apps = favorite_service.list_favorites_in_homepage(list_opt, None, workspace_id)

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [app.__dict__ for app in apps],
                "page": page,
                "page_size": page_size
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取首页收藏列表失败: {str(e)}")


# ==================== 个人智能体管理API ====================

@router.get("/personal-agents", summary="获取个人智能体列表")
async def list_personal_agents(
    workspace_id: str = Query(..., description="工作空间ID(必填)"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="关键词"),
    app_type: Optional[str] = Query(None, description="应用类型"),
    is_published: Optional[bool] = Query(None, description="是否已发布")
):
    """获取用户的个人智能体列表(workspace_id必填)"""
    try:
        list_opt = ListOption(page=page, page_size=page_size)
        filter_opt = ListAppBriefsFilter(
            keyword=keyword,
            app_types=[AppType(app_type)] if app_type else None,
            is_published=is_published
        )

        agents, total = personal_agent_service.list_personal_agents(list_opt, filter_opt, workspace_id)

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [agent.__dict__ for agent in agents],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取智能体列表失败: {str(e)}")


@router.get("/personal-agents/{app_id}", summary="获取智能体详情")
async def get_personal_agent(
    app_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取个人智能体的详细信息"""
    try:
        agent = personal_agent_service.get_personal_agent(app_id, workspace_id)
        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        return StandardResponse(
            success=True,
            message="获取成功",
            data={"agent": agent.__dict__}
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取智能体详情失败: {str(e)}")


@router.post("/personal-agents", summary="创建智能体")
async def create_personal_agent(request: CreateAgentRequest):
    """创建新的个人智能体"""
    try:
        # 将字符串转换为AppType枚举
        # 支持大小写不敏感的匹配
        app_type_str = request.app_type.upper()
        try:
            app_type = AppType[app_type_str]
        except KeyError:
            # 如果直接匹配失败,尝试通过值匹配
            app_type = None
            for member in AppType:
                if member.value == request.app_type:
                    app_type = member
                    break
            if app_type is None:
                raise ValueError(f"无效的应用类型: {request.app_type}")

        app_id = personal_agent_service.create_personal_agent(
            name=request.name,
            description=request.description,
            app_type=app_type,
            workspace_id=request.workspace_id,
            icon=request.icon,
            background=request.background,
            image=request.image,
            workflow_ids=request.workflow_ids
        )

        if not app_id:
            raise HTTPException(status_code=400, detail="创建智能体失败")

        return StandardResponse(
            success=True,
            message="创建成功",
            data={"app_id": app_id}
        )
    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建智能体失败: {str(e)}")


@router.put("/personal-agents/{app_id}", summary="更新智能体")
async def update_personal_agent(
    app_id: str,
    request: UpdateAgentRequest,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """更新个人智能体信息"""
    try:
        success = personal_agent_service.update_personal_agent(
            app_id=app_id,
            name=request.name,
            description=request.description,
            icon=request.icon,
            background=request.background,
            image=request.image,
            http_runnable=request.http_runnable,
            api_runnable=request.api_runnable,
            workflow_ids=request.workflow_ids,
            workspace_id=workspace_id
        )

        return StandardResponse(
            success=success,
            message="更新成功" if success else "更新失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新智能体失败: {str(e)}")


@router.delete("/personal-agents/{app_id}", summary="删除智能体")
async def delete_personal_agent(
    app_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """删除个人智能体"""
    try:
        success = personal_agent_service.delete_personal_agent(app_id, workspace_id)
        return StandardResponse(
            success=success,
            message="删除成功" if success else "删除失败"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除智能体失败: {str(e)}")


@router.post("/personal-agents/{app_id}/copy", summary="复制智能体")
async def copy_personal_agent(
    app_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    复制一个现有的智能体

    注意：
    - 智能体必须已配置模型、提示词等必要组件才能复制
    - 建议先保存草稿配置并发布后再复制
    """
    try:
        new_app_id = personal_agent_service.copy_personal_agent(app_id, workspace_id)
        if not new_app_id:
            raise HTTPException(
                status_code=400,
                detail="复制智能体失败：智能体配置不完整，请先完善配置"
            )

        return StandardResponse(
            success=True,
            message="复制成功",
            data={"app_id": new_app_id}
        )
    except HTTPException:
        raise
    except Exception as e:
        error_msg = str(e)

        # 根据错误类型返回不同的状态码和提示
        if "配置不完整" in error_msg or "部分组件需调整" in error_msg:
            raise HTTPException(
                status_code=400,
                detail=error_msg
            )
        else:
            raise HTTPException(
                status_code=500,
                detail=f"复制智能体失败: {error_msg}"
            )


@router.get("/personal-agents/check-name/{name}", summary="检查智能体名称")
async def check_agent_name(
    name: str,
    app_id: Optional[str] = Query(None, description="智能体ID（更新时需要）"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """检查智能体名称是否可用"""
    try:
        is_available = personal_agent_service.check_agent_name(name, app_id, workspace_id)
        return StandardResponse(
            success=True,
            message="名称可用" if is_available else "名称已被使用",
            data={"available": is_available}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"检查名称失败: {str(e)}")


@router.post("/personal-agents/copy-from-center", summary="从应用中心复制智能体")
async def copy_from_app_center(
    src_app_id: str = Body(..., embed=True, description="源应用ID"),
    dst_app_name: Optional[str] = Body(None, embed=True, description="目标应用名称"),
    workspace_id: Optional[str] = Body(None, embed=True, description="目标工作空间ID")
):
    """从应用中心复制智能体到个人空间"""
    try:
        new_app_id = personal_agent_service.copy_from_app_center(
            src_app_id=src_app_id,
            target_workspace_id=workspace_id,
            dst_app_name=dst_app_name
        )

        if not new_app_id:
            raise HTTPException(status_code=400, detail="从应用中心复制失败")

        return StandardResponse(
            success=True,
            message="复制成功",
            data={"app_id": new_app_id}
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"从应用中心复制失败: {str(e)}")


# ==================== 工作流管理API ====================

@router.get("/workflows", summary="获取工作流列表")
async def list_workflows(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="关键词搜索"),
    status: Optional[str] = Query(None, description="工作流状态 (Published/Unpublished)"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """
    获取工作流列表

    支持的筛选条件：
    - keyword: 关键词搜索（工作流名称或描述）
    - status: 工作流状态 (Published - 已发布, Unpublished - 未发布)
    """
    check_workflow_service_available()
    try:
        list_opt = ListOption(page=page, page_size=page_size)

        workflows, total = workflow_service.list_workflows(
            list_opt=list_opt,
            workspace_id=workspace_id,
            keyword=keyword,
            status=status
        )

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [workflow.__dict__ for workflow in workflows],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工作流列表失败: {str(e)}")


@router.get("/workflows/published", summary="获取已发布的工作流列表")
async def list_published_workflows(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="关键词搜索"),
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取已发布的工作流列表（可用于创建Workflow类型智能体）"""
    check_workflow_service_available()
    try:
        list_opt = ListOption(page=page, page_size=page_size)

        workflows, total = workflow_service.list_published_workflows(
            list_opt=list_opt,
            workspace_id=workspace_id,
            keyword=keyword
        )

        return StandardResponse(
            success=True,
            message="获取成功",
            data={
                "items": [workflow.__dict__ for workflow in workflows],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取已发布工作流列表失败: {str(e)}")


@router.get("/workflows/{workflow_id}", summary="获取工作流详情")
async def get_workflow(
    workflow_id: str,
    workspace_id: Optional[str] = Query(None, description="工作空间ID")
):
    """获取工作流的详细信息，包括输入参数定义"""
    check_workflow_service_available()
    try:
        workflow = workflow_service.get_workflow(workflow_id, workspace_id)

        if not workflow:
            raise HTTPException(status_code=404, detail="工作流不存在")

        return StandardResponse(
            success=True,
            message="获取成功",
            data={"workflow": workflow.__dict__}
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工作流详情失败: {str(e)}")


# ==================== Agent与知识库集成API ====================

@router.post("/agents/create-with-knowledge", summary="创建Agent并自动配置知识库")
async def create_agent_with_knowledge(request: CreateAgentWithKnowledgeRequest):
    """
    创建Agent并自动配置知识库（从源智能体复制）

    该接口会：
    1. 从指定的源智能体复制配置（模型、提示词等）
    2. 创建一个配套的知识库
    3. 配置Agent使用该知识库（仅回答知识库内容，禁止回答无关问题）

    参数说明：
    - agent_name: Agent名称（必填）
    - workspace_id: 工作空间ID（必填）
    - source_agent_id: 源智能体ID（必填，从该智能体复制配置）
    - knowledge_name: 知识库名称（可选，默认为 {agent_name}_知识库）
    - agent_description: Agent描述（可选，默认为 智能助手 - {agent_name}）

    返回值：
    - agent_id: 创建的Agent ID
    - knowledge_id: 创建的知识库ID
    - agent_name: Agent名称
    - knowledge_name: 知识库名称
    - is_copied: 是否从源智能体复制（固定为true）

    注意：
    - workspace_id 和 source_agent_id 是必填参数
    - 源智能体必须已正确配置（模型、提示词等）
    - 源智能体最好已发布
    - 只复制智能体配置，不复制知识库（会创建新的空知识库）
    - Agent默认配置为仅回答知识库内容
    - 当知识库中没有相关信息时，会提示用户无法回答
    - 创建后可通过上传文档API向知识库添加内容
    """
    if not agent_knowledge_service:
        raise HTTPException(
            status_code=503,
            detail="Agent知识库服务暂时不可用，请检查配置"
        )

    try:
        logger.info(f"开始从源智能体复制并创建知识库: agent_name={request.agent_name}, workspace_id={request.workspace_id}, source_agent_id={request.source_agent_id}")

        agent_id, knowledge_id = agent_knowledge_service.create_agent_with_knowledge(
            agent_name=request.agent_name,
            knowledge_name=request.knowledge_name,
            agent_description=request.agent_description,
            workspace_id=request.workspace_id,
            source_agent_id=request.source_agent_id
        )

        # 使用实际的知识库名称（可能是自动生成的）
        actual_knowledge_name = request.knowledge_name or f"{request.agent_name}_知识库"

        logger.info(f"Agent和知识库创建成功: agent_id={agent_id}, knowledge_id={knowledge_id}")

        return StandardResponse(
            success=True,
            message="从源智能体复制并创建成功",
            data={
                "agent_id": agent_id,
                "knowledge_id": knowledge_id,
                "agent_name": request.agent_name,
                "knowledge_name": actual_knowledge_name,
                "is_copied": True
            }
        )

    except Exception as e:
        logger.error(f"创建Agent和知识库失败: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=500,
            detail=f"创建失败: {str(e)}"
        )
